# -*- coding: utf-8 -*-
# Create your views here.
import logging
from com.jumang.util.SiteHelper import render_jum_response
from django.template.context import RequestContext
import os
from django.http import HttpResponse
import datetime
from google.appengine.ext import db
from com.jumang.model import note
from google.appengine.api import users
from com.jumang.model import uploadfile,uploadpicture
from django.http import HttpResponsePermanentRedirect
from com.jumang.model.comment import basecomment,notecomment,filecomment,pictureComment,TrackBack
from com.jumang.model.NoteCategory import NoteCategory
from com.jumang.model.FileCategory import FileCategory,PictureCategory
from com.jumang.model.Location import JumLocation
from com.jumang.model.Tag import Tag
from com.jumang.model.NoteTag import NoteTag
from com.jumang.admin.forms import FileCategoryForm,PictureCategoryForm
from com.jumang.admin.forms import NoteCategoryForm
from com.jumang.admin.forms import NoteForm
from com.jumang.model.message import message
from com.jumang.model.SystemConfig import SystemConfig
from google.appengine.api import urlfetch
import urllib
from config import JumConfig,realConfig
from xml.dom.minidom import parseString
from google.appengine.api import images
from google.appengine.api import memcache
import sys

def initPublicInfo(request,template_values):
    if template_values:
        template_values['logout']=users.create_logout_url("/")
    else:
        template_values={'logout':users.create_logout_url("/")}
    
    #realConfig.currentHome=u'http://'+request.environ['HTTP_HOST']+'/'
    #template_values['config']=realConfig



def add_note(request):
    logging.warning("add page")
    result=NoteCategory.all()
    template_values = {'categories': result,'logout':users.create_logout_url("/")}
    return render_jum_response(request,'AddNote.html',template_values)

def getTrackMessage(content):
    parse=parseString(content)
    message=''
    error=''
    errors=parse.getElementsByTagName('error')
    print errors
    if errors:
      for node in errors[0].childNodes:
        if node.nodeType == node.TEXT_NODE:
          error= node.data.strip()
          break
    if error=='1':
      messages=parse.getElementsByTagName('message')
      if messages:
        for node in messages[0].childNodes:
          if node.nodeType == node.TEXT_NODE:
            message= node.data
            break
      
    return message
    

def insert_note(request):
    logging.warning("insert page")
##    newNote=note.note(title=unicode(request.POST["title"],'utf-8'),\
##                      content=db.Text(request.POST["content"],'utf-8'))
    config=JumConfig()
    config.siteHome='http://'+request.environ['HTTP_HOST']+'/'

    form=NoteForm(request.POST)
    if form.is_valid():
##        logging.warning(form._cleaned_data())
        newNote=form.save(commit=False)
        if not dealCategory(form._cleaned_data()['category'],newNote):
            return HttpResponsePermanentRedirect('/admin/notes/')
        
## Deal with location
        allLocation=form._cleaned_data()['writeLocation']
        dealLocation(allLocation,newNote)
        
        
##Deal with tag input information
        newNote.put()
        allTag=form._cleaned_data()['tags']
        dealTag(allTag,newNote)
        
        newNote.put()
        
##Deal trackback
        if newNote.reference:
          excerpt=newNote.content
          if len(excerpt)>200:
            excerpt=excerpt[:200]
          form_fields = {
            "title": newNote.title.encode('utf-8'),
            "url": config.siteHome+'main/note/?id='+str(newNote.key().id()),
            "excerpt": excerpt.encode('utf-8'),
            "blog_name": config.siteTitle.encode('utf-8'),
          }
          logging.warning(form_fields)
          form_data = urllib.urlencode(form_fields)
          result = urlfetch.fetch(url=newNote.reference,
                                  payload=form_data,
                                  method=urlfetch.POST,
                                  headers={'Content-Type': 'application/x-www-form-urlencoded'})
          logging.warning('-----------------------')
          logging.warning(result.status_code)
##          logging.warning(result.content)
          if result.status_code == 200:
            try:
              message=getTrackMessage(result.content)
              if message:
                newNote.refResult=message
              else:
                newNote.refResult='0'
            except:
              newNote.refResult='1'
          else:
            newNote.refResult='1'
          newNote.put()   
        
    else:
        logging.warning(form)
    return HttpResponsePermanentRedirect('/admin/notes/')

def dealLocation(allLocation,newNote):
    if not allLocation:
      newNote.jumLocation=None
      return
    allLocation=allLocation.replace(u'，',u',')
    locations=allLocation.split(',')
    highLocation=None
    logging.warning(locations)
    for aLocation in locations:
##        logging.warning(aLocation)
        aLocation=aLocation.strip()
        jumLocation=JumLocation.gql('where name=:name',name=aLocation).fetch(1)
        if jumLocation:
            newLocatoin=jumLocation[0]
            if highLocation:
                if newLocatoin.area:
                  if newLocatoin.area.name!=highLocation.name:
                      newLocatoin=JumLocation(name=aLocation,area=highLocation)
                      newLocatoin.put()
        else:
            newLocatoin=JumLocation(name=aLocation)
            if highLocation:
                newLocatoin.area=highLocation
            else:
                newLocatoin.nodeType='root'
            newLocatoin.put()
        highLocation=newLocatoin
    newNote.jumLocation=newLocatoin
    
def displyLocation(locations):
    outStr='<ul>'
    for myLocation in locations:
        outStr=outStr+'<li>'+myLocation.name+'('+str(myLocation.note_set.count())+')</li>'
        if myLocation.jumlocation_set:
            outStr=outStr+'<ul>'+displyLocation(myLocation.jumlocation_set)+'</ul>'
    outStr=outStr+'</ul>'
    return outStr

    
def dealTag(allTag,newNote):
    if not allTag:
      return
    allTag=allTag.replace(u'，',u',')
    tags=allTag.split(u',')
    for aTag in tags:
        aTag=aTag.strip()
        tagObjs=Tag.gql('where name=:name',name=aTag).fetch(1)
        if tagObjs:
            newTag=tagObjs[0]
        else:
            newTag=Tag(name=aTag)
            newTag.put()
        noteTag=NoteTag(note=newNote,tag=newTag)
        noteTag.put()
    
def dealCategory(name,newNote):
    categories=NoteCategory.gql('where name=:name',\
        name=name).fetch(1)
    if categories:
        newNote.jumCategory=categories[0]
        return True
    else:
        return False

   
def editnote(request):
    
    if request.method=='GET':
        myNote=note.note.get_by_id(int(request.GET['id']))
        result=NoteCategory.all()
        myTag=u''
        for notetag in myNote.notetag_set:
            if not myTag:
                myTag=notetag.tag.name
            else:
                myTag=myTag+','+notetag.tag.name
        
        myLocations=u''
        myLocation=myNote.jumLocation
        while myLocation:
            if myLocations:
                myLocations=myLocation.name+','+myLocations
            else:
                myLocations=myLocation.name
            myLocation=myLocation.area
        
        return render_jum_response(request,'editNote.html',\
            {'note':myNote,'categories':result,'tags':myTag,\
            'location':myLocations,'logout':users.create_logout_url("/")})    
    
    if request.method=='POST':
        myNote=note.note.get_by_id(int(request.POST['id']))
##        logging.warning(myNote)
        form=NoteForm(request.POST)
        if form.is_valid():
##            logging.warning(form)
            newNote=form.save(commit=False)
            myNote.title=newNote.title
            myNote.isPublic=newNote.isPublic
            myNote.content=newNote.content
##            logging.warning(form._cleaned_data()['category'])
            if not dealCategory(form._cleaned_data()['category'],myNote):
                return HttpResponsePermanentRedirect('/admin/notes/')
                
        ## Deal with location
            allLocation=form._cleaned_data()['writeLocation']
##            logging.warning(allLocation)
            dealLocation(allLocation,myNote)
                
                
        ##Deal with tag input information
            for noteTag in myNote.notetag_set:
                noteTag.delete()
            allTag=form._cleaned_data()['tags']
            dealTag(allTag,myNote)
                
            myNote.put()
        else:
            logging.warning(form)
    return HttpResponsePermanentRedirect('/admin/notes/')
        
         

##    path = os.path.join(os.path.dirname(__file__), 'AddNote.html')
##    logging.warning(path)
##    #self.response.out.write(template.render(path, template_values))
##    return HttpResponse(template.render(path, template_values))
##    

def uploadDisplay(request):
  logging.warning("upload page")
  result=FileCategory.all()
  template_values = {'categories': result,'logout':users.create_logout_url("/")}
  return render_jum_response(request,'AddFile.html',template_values)

def uploadFile(request):
    logging.warning("upload file page")
##    logging.warning(request.FILES['file'])
##    logging.warning(request.POST["describe"])
    newFile=uploadfile.file(name=unicode(request.FILES['file']['filename'],'utf-8'),\
                      content=db.Blob(request.FILES['file']['content']),\
                      describe=db.Text(request.POST["describe"],'utf-8'))
    try:
        temp=request.POST['isPublic']
        newFile.isPublic=True
    except:
        newFile.isPublic=False
    categories=FileCategory.gql('where name=:name',\
        name=unicode(request.POST['category'],'utf-8')).fetch(1)
    if categories:
        newFile.jumCategory=categories[0]
    else:
        return HttpResponsePermanentRedirect('/admin/files/')
    
    newFile.put()
    return HttpResponsePermanentRedirect('/admin/files/')

def editfile(request):
    
    if request.method=='GET':
        myFile=uploadfile.file.get_by_id(int(request.GET['id']))
        result=FileCategory.all()
        return render_jum_response(request,'editFile.html',\
            {'file':myFile,'categories':result,
              'logout':users.create_logout_url("/")})    
    
    if request.method=='POST':
        myFile=uploadfile.file.get_by_id(int(request.POST['id']))
        myFile.name=unicode(request.POST['filename'],'utf-8')
        myFile.describe=db.Text(request.POST["describe"],'utf-8')
        try:
            temp=request.POST['isPublic']
            myFile.isPublic=True
        except:
            myFile.isPublic=False
        categories=FileCategory.gql('where name=:name',\
            name=unicode(request.POST['category'],'utf-8')).fetch(1)
        if categories:
            myFile.jumCategory=categories[0]
        else:
            return HttpResponsePermanentRedirect('/admin/files/')

        myFile.put()
        return HttpResponsePermanentRedirect('/admin/files/')


def notemanagement(request):
    logging.warning("notemanagement page")
    template_values = {}
  
    query=db.Query(note.note)
    query.order('-createTime')
    result=query.fetch(1000)
      
    template_values = {'data': result,'logout':users.create_logout_url("/")}
  
    return render_jum_response(request,'notemanagement.html',template_values)
  
def filemanagement(request):
    logging.warning("filemanagement page")
    template_values = {}
  
    query=db.Query(uploadfile.file)
    query.order('-createTime')
    result=query.fetch(1000)
      
    template_values = {'data': result,'logout':users.create_logout_url("/")}
  
    return render_jum_response(request,'filemanagement.html',template_values)

  
def deletenote(request):
    logging.warning("deletenote page")
    template_values = {}
  
    myNote=note.note.get_by_id(int(request.GET['id']))
    for noteComment in myNote.notecomment_set:
        noteComment.delete()
    for noteTag in myNote.notetag_set:
        noteTag.delete()
        
    myNote.delete()
  
    return HttpResponsePermanentRedirect('/admin/notes/')
  
def deletefile(request):
    logging.warning("deletefile page")
    template_values = {}
  
    myFile=uploadfile.file.get_by_id(int(request.GET['id']))
    for fileComment in myFile.filecomment_set:
        fileComment.delete()
    myFile.delete()
  
    return HttpResponsePermanentRedirect('/admin/files/')

def deleteFileComment(request):
    logging.warning("delete note comment page")
  
    myComment=filecomment.get_by_id(int(request.GET['id']))
    if myComment:
        myComment.delete()
  
    return HttpResponsePermanentRedirect('/main/file/?id=%s' %request.GET['pid'])

def deleteNoteComment(request):
    logging.warning("delete note comment page")
  
    myComment=notecomment.get_by_id(int(request.GET['id']))
    if myComment:
        myComment.delete()
  
    return HttpResponsePermanentRedirect('/main/note/?id=%s' %request.GET['pid'])

def deleteMessage(request):
    logging.warning("delete note comment page")
  
    myComment=message.get_by_id(int(request.GET['id']))
    if myComment:
        myComment.delete()
  
    return HttpResponsePermanentRedirect('/main/messages/')
  
  
def noteCategories(request):
    result=NoteCategory.all()
    template_values = {'data': result,'logout':users.create_logout_url("/")}
    return render_jum_response(request,'notecategories.html',template_values)
def addNoteCategory(request):
    form=NoteCategoryForm(request.POST)
    if form.is_valid():
        comment=form.save(commit=False)
        comment.put()
    return HttpResponsePermanentRedirect('/admin/noteCategories/')
def deleteNoteCategory(request):
    jumCategory=NoteCategory.get_by_id(int(request.GET['id']))
    if jumCategory:
        jumCategory.delete()
    
    return HttpResponsePermanentRedirect('/admin/noteCategories/')
def fileCategories(request):
    result=FileCategory.all()
    template_values = {'data': result,'logout':users.create_logout_url("/")}
    return render_jum_response(request,'filecategories.html',template_values)
def addFileCategory(request):
    form=FileCategoryForm(request.POST)
    if form.is_valid():
        comment=form.save(commit=False)
        comment.put()
    return HttpResponsePermanentRedirect('/admin/fileCategories/')
def deleteFileCategory(request):
    jumCategory=FileCategory.get_by_id(int(request.GET['id']))
    if jumCategory:
        jumCategory.delete()
    return HttpResponsePermanentRedirect('/admin/fileCategories/')
def locations(request):
    result=JumLocation.all().filter('nodeType = ','root')
##    result.filter('area=',None)
    if not result:
      result=JumLocation.all()
      for myLocation in result:
        if not myLocation.area:
          myLocation.nodeType='root'
          myLocation.put()
##        logging.warning(myLocation.area)
      result=JumLocation.all().filter('nodeType = ','root')
    template_values={'locations':result}
    template_values['display']=displyLocation(result)
    template_values['logout']=users.create_logout_url("/")
##    logging.warning('map='+template_values['display'])
##    logging.warning(result.count(100))
    return render_jum_response(request,'locations.html',template_values)


def deleteTrackBack(request):
  trackBack=TrackBack.get_by_id(int(request.GET['id']))
  if trackBack:
      trackBack.delete()
  
  return HttpResponsePermanentRedirect('/main/note/?id=%s' %request.GET['pid'])


def uploadPicture(request):
  if request.method == 'GET':
#    logging.warning("upload picture page")
    result=PictureCategory.all()
    template_values = {'categories': result,'logout':users.create_logout_url("/")}
    return render_jum_response(request,'AddPicture.html',template_values)
    
  elif request.method == 'POST':
    logging.warning("upload picture page")
    ##    logging.warning(request.FILES['file'])
    ##    logging.warning(request.POST["describe"])
    ##    logging.warning(request.FILES['file']['filename'])
    if request.POST["displayName"] and len(request.POST["displayName"])>0:
      realName=unicode(request.POST["displayName"],'utf-8')
    else:
      realName=unicode(request.FILES['file']['filename'],'utf-8')

    newFile=uploadpicture.Picture(name=unicode(request.FILES['file']['filename'],'utf-8'),\
                      displayName=realName,
#                      content=db.Blob(request.FILES['file']['content']),\
                      describe=db.Text(request.POST["describe"],'utf-8'))
    try:
        temp=request.POST['isPublic']
        newFile.isPublic=True
    except:
        newFile.isPublic=False
    categories=PictureCategory.gql('where name=:name',\
        name=unicode(request.POST['category'],'utf-8')).fetch(1)
    if categories:
        newFile.jumCategory=categories[0]
        try:
          data=request.FILES['file']['content']
          image=images.Image(data)
          if image.width==0 or image.height==0:
            newFile.content=db.Blob(data)
          else:
            preSize=len(data)
            while preSize>1000000 :
              image.resize(image.width*3/4,image.height*3/4)
              data=image.execute_transforms()
              preSize=len(data)
            newFile.content=db.Blob(data)
          newFile.width=image.width
          newFile.height=image.height
          
          if image.width>realConfig.displayWidth:
            newFile.displayWidth=realConfig.displayWidth
            newFile.displayHeight=realConfig.displayWidth*image.height/image.width
          else:
            newFile.displayWidth=image.width
            newFile.displayHeight=image.height
        except:   
            logging.warning('-----------------error--------------'+str(sys.exc_info()[0])+'--'+str(sys.exc_info()[1]))
            newFile.content=db.Blob(request.FILES['file']['content'])
            newFile.displayWidth=realConfig.displayWidth
            newFile.displayHeight=realConfig.displayWidth
        newFile.put()
    return HttpResponsePermanentRedirect('/admin/pictures/')
    
  
def pictures(request):
  logging.warning("Picture management page")
  template_values = {}
  
  query=db.Query(uploadpicture.Picture)
  query.order('-createTime')
  result=query.fetch(1000)
    
  template_values = {'data': result,'logout':users.create_logout_url("/")}
  
  return render_jum_response(request,'picturemanagement.html',template_values)
  
def editPicture(request):
  if request.method=='GET':
      myFile=uploadpicture.Picture.get_by_id(int(request.GET['id']))
      result=PictureCategory.all()
      return render_jum_response(request,'editPicture.html',\
          {'file':myFile,'categories':result,
            'logout':users.create_logout_url("/")})    
  
  if request.method=='POST':
      myFile=uploadpicture.Picture.get_by_id(int(request.POST['id']))
      myFile.name=unicode(request.POST['filename'],'utf-8')
      myFile.displayName=unicode(request.POST['displayName'],'utf-8')
      myFile.describe=db.Text(request.POST["describe"],'utf-8')
      try:
          temp=request.POST['isPublic']
          myFile.isPublic=True
      except:
          myFile.isPublic=False
      categories=PictureCategory.gql('where name=:name',\
          name=unicode(request.POST['category'],'utf-8')).fetch(1)
      if categories:
          myFile.jumCategory=categories[0]
          myFile.put()
  
      return HttpResponsePermanentRedirect('/admin/pictures/')
  
def deletePicture(request):
  logging.warning("delete picture page")
  template_values = {}
  
  myFile=uploadpicture.Picture.get_by_id(int(request.GET['id']))
  for fileComment in myFile.picturecomment_set:
      fileComment.delete()
  myFile.delete()
  
  return HttpResponsePermanentRedirect('/admin/pictures/')
  
def deletePictureComment(request):
  logging.warning("delete picture comment page")
  
  myComment=pictureComment.get_by_id(int(request.GET['id']))
  if myComment:
      myComment.delete()
  
  return HttpResponsePermanentRedirect('/main/picture/?id=%s' %request.GET['pid'])
  
def pictureCategories(request):
  result=PictureCategory.all()
  template_values = {'data': result,'logout':users.create_logout_url("/")}
  return render_jum_response(request,'picturecategories.html',template_values)
  
def addPictureCategory(request):
  form=PictureCategoryForm(request.POST)
  if form.is_valid():
      comment=form.save(commit=False)
      comment.put()
  return HttpResponsePermanentRedirect('/admin/pictureCategories/')
  
def deletePictureCategory(request):
  jumCategory=PictureCategory.get_by_id(int(request.GET['id']))
  if jumCategory:
      jumCategory.delete()
  return HttpResponsePermanentRedirect('/admin/pictureCategories/')

def updateCinfiguration(request,name):
  if request.POST.__contains__(name):
    if request.POST[name]:
      logging.info(name+' '+request.POST[name])
      query=SystemConfig.gql("where name=:name",name=name)
      data=query.fetch(1)
      if data:
        config=data[0]
        config.value=db.Text(request.POST[name],'utf-8')
      else:
        config=SystemConfig(name=unicode(name,'utf-8'),
                            value=db.Text(request.POST[name],'utf-8'))
      config.put()
      return config
    else:
      return None
  else:
    return None

  
def config(request):
  if request.method=='GET':
    return render_jum_response(request,'configure.html',{'logout':users.create_logout_url("/")})    
  
  if request.method=='POST':
    #todo update db and memcache
    updateCinfiguration(request,realConfig.userNameName)
    updateCinfiguration(request,realConfig.passwordName)
    updateCinfiguration(request,realConfig.privatePwdName)
    result=updateCinfiguration(request,realConfig.linksName)  
    if result:
      memcache.set(realConfig.linksName,result.value)
    return HttpResponsePermanentRedirect('/admin/config/')
